﻿using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using Prism.Services.Dialogs;
using System.Collections.ObjectModel;
using WPF.Core;
using WPF.Core.Dtos;
using WPF.Core.Services;
using static WPF.Core.Dtos.ToDoModel;

namespace WPF.ToDo.ViewModels
{
    public partial class ToDoViewModel : NavigateViewModel
    {
        private readonly IToDoService appService;
        private readonly IHostDialogService dialog;

        [ObservableProperty]
        private ToDoPagingInfo paging;

        [ObservableProperty]
        private ObservableCollection<ToDoModel> gridModelList;


        public ToDoViewModel(IToDoService appService, IHostDialogService dialog)
        {
            GridModelList = new ObservableCollection<ToDoModel>();
            this.appService = appService;
            Paging = new ToDoPagingInfo()
            {
                PageNumber = 1,
                PageSize = 1,
            };
            this.dialog = dialog;
        }

        [RelayCommand]
        private async Task Add()
        {

            var dialogResult = await dialog.ShowDialogAsync("CreateToDoView");

            if (dialogResult.Result == ButtonResult.OK)
            {
                await GetAllAsync();
            }
        }

        [RelayCommand]
        private async Task Search()
        {
            await GetAllAsync();
        }

        [RelayCommand]
        private async Task Delete(ToDoModel model)
        {
            var dialogResult = await dialog.Question();
            if (dialogResult.Result != ButtonResult.OK) return;

            //删除数据库数据
            await appService.Delete(model.Id);
            var todo = GridModelList.FirstOrDefault(x => x.Id == model.Id);
            if (todo != null)
            {
                //界面数据删除
                GridModelList.Remove(todo);
            }
        }

        [RelayCommand]
        private async Task Edit(ToDoModel model)
        {
            DialogParameters param = new DialogParameters();
            param.Add("Value", model);
            var dialogResult = await dialog.ShowDialogAsync("CreateToDoView", param);
            if (dialogResult.Result == ButtonResult.OK)
            {
                await GetAllAsync();
            }
        }

        [RelayCommand]
        public async Task Pageing()
        {
            await GetAllAsync();
        }

        /// <summary>
        /// 获取所有待办事项
        /// </summary>
        /// <returns></returns>
        private async Task GetAllAsync()
        {
            var models = await appService.GetAll(paging);
            GridModelList.Clear();
            if (models != null)
            {
                foreach (var model in models)
                {
                    GridModelList.Add(model);
                }
            }
        }




    }
}
